/**
 * 
 */
package escola.spring.datasource;

import java.sql.Driver;
import java.sql.SQLFeatureNotSupportedException;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.logging.Logger;

import org.springframework.jdbc.datasource.SimpleDriverDataSource;
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;

import escola.logic.database.DatabaseLogic;

/**
 * @author Jonathan
 *
 */
public class DataSourceRouter extends AbstractRoutingDataSource {

	private String driverClassName;
	
	private String url;
	
	private String username;
	
	private String password;
	
	private Set<String> databases;
	
	private DatabaseLogic logic;
	
	public String getDriverClassName() {
		return driverClassName;
	}

	public void setDriverClassName(String driverClassName) {
		this.driverClassName = driverClassName;
	}

	public String getUrl() {
		return url;
	}

	public void setUrl(String url) {
		this.url = url;
	}

	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public Set<String> getDatabases() {
		if (databases == null) {
			databases = logic.getDataBases();
		}
		return databases;
	}

	public void setDatabases(Set<String> databases) {
		this.databases = databases;
	}

	public DatabaseLogic getLogic() {
		return logic;
	}

	public void setLogic(DatabaseLogic logic) {
		this.logic = logic;
	}
	
	@Override
	public void afterPropertiesSet() {
		Map<Object, Object> map = new HashMap<Object, Object>();
		for (String dataBase : getDatabases()) {
			map.put(dataBase.trim().toLowerCase(), new SimpleDriverDataSource(getDriver(), getUrl() + dataBase, getUsername(), getPassword()));
		}
		setTargetDataSources(map);
		setDefaultTargetDataSource(map.get(databases.iterator().next().toLowerCase()));
		DataSourceContextHolder.setServerURL(getUrl());
		super.afterPropertiesSet();
	}

	private Driver getDriver() {
		try {
			return (Driver) Class.forName(getDriverClassName()).newInstance();
		} catch (InstantiationException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
		return null;
	}

	@Override
	protected Object determineCurrentLookupKey() {
		return DataSourceContextHolder.getDataSourceName();
	}
	
	public boolean hasDatabases(String database) {
		return getDatabases().contains(database);
	}

	@Override
	public Logger getParentLogger() throws SQLFeatureNotSupportedException {
		return null;
	}

}
